package gy.com.sansharescuesystem.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import java.util.List;

/**
*APP管理工具类
*@author huangbo
*create at 2016/10/21 10:42
*/
public class AppUtils {
    public static int getVersion(Context context)// 获取版本号
    {
        PackageInfo pi = null;
        try {
            pi = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return pi !=null ? pi.versionCode : 0;
    }

    /**
     * 获得当前版本的versionName
     *
     * @return String
     */
    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Unknown";
    }


    public static boolean isAppAlive(Context context, String processName) {
        if (context == null) {
            return false;
        }

        int pid = android.os.Process.myPid();
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfoList = manager.getRunningAppProcesses();
        if (processInfoList == null || processInfoList.isEmpty()) {
            return false;
        }

        for (ActivityManager.RunningAppProcessInfo processInfo : processInfoList) {
            if (processInfo != null && processInfo.pid == pid
                    &&  processInfo.processName.equals(processName)) {
                return true;
            }
        }
        return false;
    }

    public static String getAppName(Context pContext) {
        PackageManager packageManager = null;
        ApplicationInfo applicationInfo;
        try {
            packageManager =pContext.getPackageManager();
            applicationInfo = packageManager.getApplicationInfo(pContext.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            applicationInfo = null;
        }
        String applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
        return applicationName;
    }

}
